import React, {Component} from 'react';
import _ from 'underscore'

export class UploadFileStore {
  constructor() {
    this.$state = {
      files: [],
      id: 'input-' + new Date().getTime()
    }

    this.state = this.state.bind(this);
    this.emit = this.emit.bind(this);
    this.getFiles = this.getFiles.bind(this);
  }

  state() {
    return this.$state;
  }

  emit(view = this.viewInstance, newState) {
    let that = this;
    view.setState(_.extend(this.$state, newState));
  }

  getFiles() {
    return this.$state.files;
  }

  resetFiles() {
    this.$state.files = [];

    this.emit();
  } // resetFiles
}

export default class UploadFile extends Component {
  constructor(props, context) {
    super(props, context);

    this.scope = this.props.scope;
    this.scope.viewInstance = this;
    this.state = this.scope.state();
  }

  addFileHandler(e) {
    let { addCallback } = this.props;

    if (!addCallback || addCallback && _.isFunction(addCallback) && addCallback(e.target)) {
      this.scope.emit(this, {
        files: _.map(e.target.files || [], item => item.name)
      });
    } else {
      e.target.value = null;

      this.scope.resetFiles();
    }
  } // addFileHandler

  render() {
    let height = this.props.height+'px';
    return (
      <div>
        <div className="input-file" style={{height}}>
          <input
            id={this.state.id}
            key="input"
            className="file"
            type="file"
            ref="file"
            multiple={this.props.multiple}
            name={this.props.name}
            onChange={this.addFileHandler.bind(this)} />
          <input
            readOnly
            key="display"
            type="text"
            className="text input-text"
            style={{
              width:this.props.width+'px',
              lineHeight:height,
              height,
            }}
            value={this.state.files.toString()}
            placeholder={this.props.nullFileName} />
          <label htmlFor={this.state.id} style={{cursor:'pointer'}}>
            <span
              className="text btn-blue"
              style={{lineHeight:(this.props.height-2)+'px'}}>
              {this.props.label}
            </span>
          </label>
        </div>
        {
          this.props.error
            ? (<div style={{marginTop:'5px'}}><span className="msg-error">{this.props.error}</span></div>)
            : null
        }
      </div>
    );
  }
}

UploadFile.defaultProps = {
  // upload stroe instance
  scope: new UploadFileStore(),
  // define name attribute for form submit
  name: undefined,
  // define callback before add file.
  addCallback: null,
  // text description
  label: '浏览...',
  // default height
  height:32,
  // default input component width
  width: 200,
  // default file name label
  nullFileName: '还未选择文件',
  // multiple files
  multiple:false,
  // error message
  error:null
}
